package com.tomriff.moneymaker.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Moneymaker implements EntryPoint {

	final MoneymakerMessages messages = GWT.create(MoneymakerMessages.class);

	// Panels
	final RootPanel searchPanel = RootPanel.get("search");
	Panel results = RootPanel.get("results");
	Panel pageTitle = RootPanel.get("page-title");
	FlowPanel resultPanel = new FlowPanel();

	// Buttons
	Button searchButton = new Button(messages.search());
	Button createProductButton = new Button(messages.createProduct());

	Label title = new Label(messages.welcome());
	TextBox searchText = new TextBox();
	final DialogBox createProductDialog = new DialogBox();
	Label searchTerm = new Label();

	/**
	 * Initial Method when App is started
	 */
	@Override
	public void onModuleLoad() {
		pageTitle.add(title);

		searchText.setWidth("300px");
		searchPanel.add(searchText);
		searchText.addKeyUpHandler(new KeyUpHandler() {
			@Override
			public void onKeyUp(KeyUpEvent event) {
				searchForProducts();
			}
		});
		searchPanel.add(searchButton);
	}

	private void searchForProducts() {
		int numberOfResults = 0;
		searchTerm.setText(numberOfResults + " " + messages.resultsFor() + " "
				+ searchText.getValue());
		results.clear();
		resultPanel.clear();
		resultPanel.add(searchTerm);

		// If product can not be found, show button to create it
		if (numberOfResults == 0) {
			resultPanel.add(createProductButton);
			// Create a Dialog for new Product
			showCreateProductDialog();
		}
		results.add(resultPanel);
	}

	private void showCreateProductDialog() {
		createProductDialog.clear();
		Widget createProductPanel = new CreateProduct(searchText.getValue(),
				createProductDialog);
		createProductDialog.setTitle(messages.createProduct());
		// createProductDialog.setText(messages.createProduct());
		createProductDialog.add(createProductPanel);
		createProductButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				// Show the dialog when button is pressed
				createProductDialog.center();
				createProductDialog.show();
			}
		});
	}
};
